package com.reshare.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.reshare.base.BaseService;
import com.reshare.bean.Category;
import com.reshare.bean.Commodity;
import com.reshare.bean.CommodityImg;
import com.reshare.bean.User;
import com.reshare.mapper.CategoryMapper;
import com.reshare.mapper.CommodityImgMapper;
import com.reshare.mapper.CommodityMapper;
import com.reshare.model.CommodityModel;
import com.reshare.query.CommodityQuery;
import com.reshare.utils.AssertUtil;
import com.reshare.utils.LoginUserUtil;
import com.reshare.utils.UUIDSerialUtil;
import com.reshare.utils.UploadUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;


/*功能描述
 * @author ahm
 */
@Service
public class CommodityService extends BaseService<Commodity,Integer> {

    @Autowired(required = false)
    private CommodityMapper commodityMapper;

    @Autowired(required = false)
    private CategoryMapper categoryMapper;

    @Autowired(required = false)
    private CommodityImgMapper commodityImgMapper;
//

    /*
    * 更据ID 查询Commodity
    * */
    public Commodity findById(Integer id){
        AssertUtil.isTrue(id==null,"待编辑的商品为空");
        Commodity commodity = commodityMapper.findById(id);
        AssertUtil.isTrue(commodity==null,"未发现该商品");
        return commodity;

    }


    public Map<String,Object> findCommodityList(CommodityQuery commodityQuery){
        PageHelper.startPage(commodityQuery.getPage(),commodityQuery.getLimit());
        List<Commodity> commodities = commodityMapper.selectAllCommodityByParams(commodityQuery);
        PageInfo<Commodity> pageInfo = new PageInfo<>(commodities);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code",0);
        hashMap.put("msg","查询成功");
        hashMap.put("count",pageInfo.getTotal());
        hashMap.put("data",pageInfo.getList());
        return hashMap;

    }


    public void addCommodity(MultipartFile[] multipartFiles, HttpServletRequest request, Commodity commodity, Integer categoryId){

        // 参数校验
        checkCommodityParams(commodity.getTitle(),commodity.getPrice(),commodity.getOldPrice(),commodity.getQuality(),commodity.getRepertory(),commodity.getSwiper(),commodity.getDescription());
        AssertUtil.isTrue(multipartFiles==null,"请选择上传的图片");
        AssertUtil.isTrue(categoryId==null,"请输入分类");
        AssertUtil.isTrue(categoryMapper.findById(categoryId)==null,"不存在该分类，请重新选择");
        // 设置默认值
        // 设置轮播图
        if (commodity.getSwiper()==null){
            commodity.setSwiper(false);
        }
        // 设置商品编号
        commodity.setSerial(UUIDSerialUtil.getSerial());
        // categoryId
        Category category = new Category();
        category.setId(categoryId);
        commodity.setCategory(category);
        // 点击量
        commodity.setClickCount(0);
        // 收藏量
        commodity.setCollectCount(0);
        // 商品状态
        commodity.setState(1); // 默认为1 出售中
        // 发布者
        int userId = LoginUserUtil.releaseUserIdFromCookie(request);
        User user = new User();
        user.setId(userId);
        commodity.setUser(user);
        // 发布时间
        commodity.setPublishDate(new Date());
         // 添加商品获得 商品的 id
        int result = commodityMapper.insertCommodity(commodity);
        AssertUtil.isTrue(result<1,"商品添加失败");
        // 商品对应的图片集
        List<CommodityImg> commodityImgs = new ArrayList<>();
        // 批量上传图片
        for (MultipartFile multipartFile:multipartFiles){
            // 参数校验
            AssertUtil.isTrue(multipartFile.isEmpty(),"上传文件失败");
            try {
                // 生成新的文件名
                String fileName = System.currentTimeMillis()+multipartFile.getOriginalFilename();
                // 获取图片要上传的路径
                File fileDir = UploadUtils.getImgDirFile();
                // 真实路径
                File newFile = new File(fileDir.getAbsolutePath() + File.separator + fileName);
                multipartFile.transferTo(newFile);
                // 添加商品图片
                CommodityImg commodityImg = new CommodityImg();
                    // 对应商品ID
                commodityImg.setCommodityId(commodity.getId());
                    // 图片路径
                commodityImg.setImgSrc(fileName);
                commodityImgs.add(commodityImg);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        // 批量图片入库

        AssertUtil.isTrue(commodityImgMapper.insertBatch(commodityImgs)!=commodityImgs.size(),"添加失败，图片上传失败");
        System.out.println("图片入库成功");
        // 默认将第一张图片作为封面
        commodity.setCoverImage(commodityImgs.get(0).getImgSrc());

        AssertUtil.isTrue(commodityMapper.updateCoverImgById(commodity)<1,"添加失败，未发现封面");







    }

    private void checkCommodityParams(String title, Double price, Double oldPrice, String quality, Integer repertory, Boolean swiper, String description) {
        AssertUtil.isTrue(StringUtils.isBlank(title),"标题不可以为空");
        AssertUtil.isTrue(price==null,"价格不能为空");
        AssertUtil.isTrue(oldPrice==null,"原来价格不能为空");
        AssertUtil.isTrue(StringUtils.isBlank(quality),"品质描述不能为空");
        AssertUtil.isTrue(repertory==null,"请填写库存");
//        AssertUtil.isTrue(swiper,"请设置是否需要轮播该商品图");
        AssertUtil.isTrue(StringUtils.isBlank(description),"请输入商品描述");
    }


    public void delCommodity(Integer commodityId, Integer userId) {
        // 校验参数
        AssertUtil.isTrue(commodityId==null,"该商品不存在");
//        AssertUtil.isTrue(userId==null,"该用户不存在");
        // 修改状态 state= 3
        AssertUtil.isTrue(commodityMapper.updateCommodityState(commodityId)<1,"更新失败");

    }
}
